package com.zhuoyue.common.aop.auth;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhuoyue.biz.core.api.domain.AppUserHomeRelationDO;
import com.zhuoyue.biz.core.api.service.impl.AppUserHomeRelationService;
import com.zhuoyue.common.jwt.util.JwtOperator;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author wjming
 * @ClassName: AuthMasterAspect
 * @Description: 管理员验证接口
 * @Date 2021-07-09 9:45
 */
@Aspect
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AuthMasterAspect {
    private final JwtOperator jwtOperator;

    private final RedisTemplate redisTemplate;

    private final AppUserHomeRelationService userHomeRelationService;
    /**
     * 字段截取
     */
    private static final String BEARER = "Bearer ";

    @Around("@annotation(com.zhuoyue.common.aop.auth.AuthMaster)")
    public void checkLogin(JoinPoint point) throws Throwable {
        List<AppUserHomeRelationDO> appUserHomeRelationDos = checkToken();
        // 获取方法签名
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        // 获取方法
        Method method = methodSignature.getMethod();
        AuthMaster paramsTake = method.getAnnotation(AuthMaster.class);
        // 获取操作描述的属性值
        String collectionType = paramsTake.authCollection();
        switch (collectionType) {
            case "room":
                break;
            case "zigbeeDevice":
                break;
            case "infraredDevice":
                break;
            case "wifiDevice":
                break;
            case "localScene":
                break;
            case "automate":
                break;
            default:
                break;
        }

    }

    private List<AppUserHomeRelationDO> checkToken() {
        HttpServletRequest request = getHttpServletRequest();
        String tokenStr = request.getHeader("Authorization");
        String orgCode = request.getHeader("organizationCode");

        //2.校验token是否合法&是否过期，如果不合法或已过期直接抛异常，:如果合法放行
        //validateToken用来校验token是否合法或过期
        String token = null;
        if (tokenStr.startsWith(BEARER)) {
            token = tokenStr.substring(7);
        }
        Boolean isValid = jwtOperator.validateToken(token);
        if (!isValid) {
            throw new SecurityException("token不合法");
        }

        //3.如果校验成功，就将用户的信息设置到request的attribute里面
        Claims claims = jwtOperator.getClaimsFromToken(token);
        String idStr = claims.get("id").toString();
        List<AppUserHomeRelationDO> list = userHomeRelationService.list(Wrappers.<AppUserHomeRelationDO>lambdaQuery()
                .eq(AppUserHomeRelationDO::getAppUserId, idStr));
        return list;
    }

    private HttpServletRequest getHttpServletRequest() {
        //1.从header里面获取token
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        return attributes.getRequest();
    }

}
